package timers

import (
	"context"
	"gitee.com/mootok/mootok/src/external_service/transcoding"
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/services/video"
	"gitee.com/mootok/mootok/src/storage/database"
	"gitee.com/mootok/mootok/src/utils/logging"
	log "github.com/sirupsen/logrus"
	"time"
)

func queryPfopTasks(duration time.Duration) {
	logger := logging.LogService("Timer.QueryPfopTasks")
	ticker := time.NewTicker(duration)
	quit := make(chan struct{})
	go func() {
		for {
			select {
			case <-ticker.C:
				logger.Info("Querying video pfops...")
				var tasks []models.Video
				database.Client.
					Where("job_id != ?", "").
					Find(&tasks, &models.Video{Status: video.StatusTranscoding})
				if len(tasks) == 0 {
					logger.Info("No pending pfop videos.")
					continue
				}
				for i, elem := range tasks {
					taskLogger := logger.WithFields(log.Fields{
						"user_id":  elem.UserId,
						"video_id": elem.ID,
						"job_id":   elem.JobId,
					})
					ret, err := transcoding.Instance.QueryTranscodingProgress(elem.JobId)
					if err != nil {
						taskLogger.Warningf("progress query failed: %v", err)
						continue
					}
					if ret == transcoding.StatusFinished {
						taskLogger.Info("pfop finished, publish video")
						tasks[i].Status = video.StatusPublished
						go func() {
							if err := FeedService.PushToFans(context.Background(), tasks[i]); err != nil {
								taskLogger.Errorf("failed to push new video to fans feed : %v", err)
							}
						}()
					} else if ret == transcoding.StatusFailed {
						taskLogger.Warningf("pfop failed")
						tasks[i].Status = video.StatusTranscodeFailed
					}
					if err := database.Client.Select("status").Updates(tasks[i]).Error; err != nil {
						taskLogger.Errorf("failed to update task: %v", err)
						continue
					}
				}
				// Update completed
				logger.Infof("processed %d tasks.", len(tasks))

			case <-quit:
				ticker.Stop()
				return
			}
		}
	}()
}